package com.ray.test.mock;

import com.github.jsonzou.jmockdata.JMockData;
import com.ray.test.util.ClassInstanceUtil;
import com.ray.test.util.PropertyUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * @author bo shen
 * @Description: 类型
 * @Class: ClassDataMock
 * @Package com.ray.test.mock
 * @date 2019/12/12 14:47
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class ClassDataMock implements DataMock {
    @Override
    public Object dataMocker(Class<?> clazz, Method method, Parameter parameter) {
        Object value = null;
        //
        Map<Class<?>,Object> result =  MockConfig.getResult().get();
        if(result != null && result.containsKey(clazz)){
            value = result.get(clazz);
        }else {
            try{
                value = JMockData.mock(clazz, MockConfig.getMockConfig());
            }catch (Exception e){
                log.info("jmockData对象异常--尝试手动实例化,{}",e.getMessage());
                try {
                     value = ClassInstanceUtil.getObject(clazz);
                }catch (Exception e1){
                    log.info("实例化对象错误,{}",e.getMessage());
                }
            }
        }
        //对于参数进行全局替换
        replace(value);
        //替换方法域参数
        if(method != null){
            replaceMethod(method.getName(), value);
        }
        return value;
    }

    private static void replace(Object bean) {
        if(bean == null)return;
        for (String key : MockConfig.getDefaultConifg().keySet()) {
            try {
                PropertyUtils.setProperty(bean, key, MockConfig.getDefaultConifg().get(key));
            } catch (Exception e) {
                log.info("属性:{}不存在，或类型不一致", key);
            }
        }
    }

    private static void replaceMethod(String method, Object bean) {
        if(bean == null)return;
        Map<String, Object> methodConfig = MockConfig.getDefaultMethodConifg().get(method);
        if (methodConfig != null) {
            for (String key : methodConfig.keySet()) {
                try {
                    PropertyUtils.setProperty(bean, key, methodConfig.get(key));
                } catch (Exception e) {
                    log.info("属性:{}不存在，或类型不一致", key);
                }
            }
        }
    }
}
